// component/ui/z-form-popup/z-form-popup.js
let customFormControls = require('../common/custom-form-controls')
const app = getApp();
Component({
  relations: {
    'customFormControls': {
      type: 'descendant',
      target: customFormControls,
    }
  },
  /**
   * 组件的配置
   */
  options: {
    styleIsolation: 'isolated',
    pureDataPattern: /^_/
  },

  /**
   * 组件的属性列表
   */
  properties: {
    isTop: {
      type: Boolean,
      value: false,
    },
    popupType: {
      type: String,
      value: 'dropdown',
    },
    leftBtn: {
      type: String,
      value: 'back',
    },
    title: {
      type: String,
      value: '',
    },
    scroll: {
      type: Boolean,
      value: false,
    },
    isOpen: {
      type: Boolean,
      value: false,
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    top: 0,
    isShow: false,
    _form: {},
    _label: {},
  },

  /**
   * 组件的数据监听
   */
  observers: {
    isOpen(val) {
      this.setData({
        isShow: val
      })
    },
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'children', {
        get: () => this.getRelationNodes('customFormControls') || [],
      });
    },
    attached() {
      const {
        isTop
      } = this.data
      isTop && this.setData({
        top: app.globalData.navHeight,
      })
    },
    detached() {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onConfirm() {
      let verify = [];
      (this.children || []).forEach((child) => {
        if (child.validator) {
          verify.push(child.validator())
        }
        child.onConfirm()
      });
      verify = verify.filter(item => {
        return !item
      })
      if (verify.length) {
        this.data._form = {}
        this.data._label = {}
      } else {
        this.triggerEvent('confirm', {
          form: this.data._form,
          label: this.data._label
        })
        this.onMaskClose()
      }
    },

    onReset() {
      (this.children || []).forEach((child) => child.onReset());
      this.triggerEvent('reset')
    },

    onMaskClose() {
      this.setData({
        isShow: false
      })
      this.triggerEvent('close')
    },

    onMaskMove() {
      return false
    },

    onClear(current, prop) {
      (this.children || []).forEach((child) => {
        if (child !== current && child.data.prop === prop) {
          child.onClear()
        }
      });
    },

    onBack() {
      this.onMaskClose()
    },


  }
})